package com.guapi.service;

import java.io.IOException;
import java.net.MalformedURLException;

import com.guapi.model.ContentSearchResult;

public class ContentSearchService {

	final QueryResultUnmarshaller unmarshaller;
	private final String apiKey;
	final QueryFetcher queryFetcher;

	public ContentSearchService(String apiKey) {
		this(apiKey, new URLQueryFetcher(), new JaxbQueryResultUnmarshaller());
	}
	
	public ContentSearchService(String apiKey, QueryFetcher queryFetcher, QueryResultUnmarshaller queryResultUnmarshaller) {
		this.apiKey = apiKey;
		this.queryFetcher = queryFetcher;
		this.unmarshaller = queryResultUnmarshaller;
	}
	
	public ContentSearchResult queryFor(final String apiUrl) throws ApiQueryException {
		
		if (apiUrl.contains("api_key=")) {
			throw new ApiQueryException("The apiUrl should not contain an api key");
		}
		
		try {
			return (ContentSearchResult) unmarshaller.unmarshall(queryFetcher.fetchQuery(apiUrl + key()));
		} catch (MalformedURLException e) {
			throw new ApiQueryException("Could not query API", e);
		} catch (IOException e) {
			throw new ApiQueryException("Could not query API", e);
		} catch (ApiUnmarshallException e) {
			throw new ApiQueryException("Could not unmarshall query", e);
		}
	}
	
	private String key() {
		return "&api_key=" + apiKey;
	}
}
